package com.isoft.service.email;


import com.alibaba.fastjson.JSON;
import com.isoft.entity.vo.LoginParam;
import com.isoft.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author LiuGaoMing
 * @version 1.0
 * @description:
 * @date 2024/6/20 10:27
 */
@Component
public class CommonService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ThreadService threadService;

    /**
     * 发送邮箱权限校验码
     * @param emailJson
     * @return
     */

    public R getRequestPermissionCode(String emailJson) {
        // 非空校验
        if (StringUtils.isBlank(emailJson)) return R.error(HttpStatusEnum.PARAM_ILLEGAL);
        // JSON转换，提取email的值
        String email = JSON.parseObject(emailJson).getString("email");
        if (email == null) {
            return R.error(HttpStatusEnum.PARAM_ILLEGAL);
        }
        email = email.trim();
        // 随机生成权限码
        String permissionCode = UUID.randomUUID().toString();
        // 存入redis,设置自定义Key,缓存10s,
        redisTemplate.opsForValue().set(RedisConstant.EMAIL_REQUEST_VERIFY + email, permissionCode, RedisConstant.EXPIRE_TEN_SECOND, TimeUnit.SECONDS);
        return R.ok().data("permissionCode", permissionCode);
    }

    /**
     * 发送邮箱验证码
     * @param loginParam
     * @return
     */
    public R sendEmailCode(LoginParam loginParam) {
        if (loginParam == null) return R.error(HttpStatusEnum.PARAM_ILLEGAL);
        // 获取权限码和邮箱
        String email = loginParam.getEmail();
        // 随机生成6位数字验证码
        String code = StringUtil.randomSixCode();
        // 正文内容
        String content = "亲爱的用户：\n" +
                "您此次的验证码为：\n\n" +
                code + "\n\n" +
                "此验证码5分钟内有效，请立即进行下一步操作。 如非你本人操作，请忽略此邮件。\n" +
                "感谢您的使用！";
        // 发送验证码
        threadService.sendSimpleMail(email, "您此次的验证码为：" + code, content);
        // 丢入缓存，设置5分钟过期
        redisTemplate.opsForValue().set(RedisConstant.EMAIL + email, code, RedisConstant.EXPIRE_FIVE_MINUTE, TimeUnit.SECONDS);
        return R.ok();
    }
}


